import React, { useState } from 'react'
import Product from './Product'
import Cart from './Cart'

export default function Shopping() {
    // 图书的数据
    const [books, setBooks] = useState([
        {
            id: 1,
            imgname: 'https://img1.baidu.com/it/u=1000375653,4052007938&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=652',
            title: 'Python实战开发',
            content: '精通Python学习指南',
            price: 234
        },
        {
            id: 2,
            imgname: 'https://img1.baidu.com/it/u=1000375653,4052007938&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=652',
            title: 'Java实战开发',
            content: '精通Java学习指南',
            price: 674
        },
        {
            id: 3,
            imgname: 'https://img1.baidu.com/it/u=1000375653,4052007938&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=652',
            title: 'H5实战开发',
            content: '精通H5学习指南',
            price: 345
        },
        {
            id: 4,
            imgname: 'https://img1.baidu.com/it/u=1000375653,4052007938&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=652',
            title: '测试框架开发',
            content: '精通测试框架学习指南',
            price: 123
        }
    ])
    //购物车数据
    const [cartData, setCartData] = useState([])
    //点击按钮加购物车
    const addCartDataEvent = (id) => {
        //拿到商品编号过后，判断这个商品是否在购物车
        const index = cartData.findIndex(item=>item.id == id)
        if(index !== -1){
            alert("商品已经存在")
        }else{
            //加入商品到购物车列表
            const obj = books.find(item=>item.id == id)
            obj.count = 1 //购买数量
            obj.status = false //选中状态
            cartData.push(obj)
            setCartData([...cartData])
        }
    }
    //修改指定商品的数量
    const changeCountParent = (id,val)=>{
        const obj = cartData.find(item=>item.id == id)
        obj.count+=val
        setCartData([...cartData])
    }
    //修改商品的选中状态
    const changeProductStatus = (id)=>{
        const obj = cartData.find(item=>item.id == id)
        obj.status = !obj.status
        setCartData([...cartData])
    }
    return (
        <div style={{ width: "1200px", margin: "0 auto" }}>
            <h2>产品</h2>
            <Product books={books} addCartParent={addCartDataEvent}></Product>
            <h2>购物车</h2>
            <Cart 
            cartData={cartData} 
            changeCountParent={changeCountParent}
            changeProductStatus={changeProductStatus}></Cart>
        </div>
    )
}
